package com.maxmlr.nio.server;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

/**
 * @ClassName TcpEchoserver
 * @Description TODO
 * @Author maxiao
 * @Date 2020/4/9 下午10:04
 * @Version V1.0
 */
public class TcpEchoserver implements Runnable {

    private InetSocketAddress inetSocketAddress;

    public TcpEchoserver(int port) {
        this.inetSocketAddress = new InetSocketAddress(port);
    }

    @Override
    public void run() {
        System.out.println("启动服务器");
        Charset charset = Charset.forName("utf-8");
        ServerSocketChannel channel = null;
        Selector selector = null;

        try {
            //选择器
            selector = Selector.open();
            //服务器通道
            channel = ServerSocketChannel.open();
            //
            channel.configureBlocking(false);

            //设置服务器端口，最大连接数 100
            channel.bind(inetSocketAddress, 100);
            //服务器通道只对 tcp
            channel.register(selector, SelectionKey.OP_ACCEPT);

        } catch (Exception e) {
            e.printStackTrace();
        }
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        RequestHandler requestHandler = new RequestHandler();
        try {
            while (!Thread.currentThread().isInterrupted()) {
                int select = selector.select();
                if (select == 0) {
                    continue;
                }
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = keys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isAcceptable()) {
                        ServerSocketChannel channel1 = (ServerSocketChannel) key.channel();
                        SocketChannel accept = channel1.accept();
                        accept.configureBlocking(false);
                        accept.register(selector, SelectionKey.OP_READ);
                    }

                    if (key.isReadable()) {
                        SocketChannel channel1 = (SocketChannel) key.channel();
                        channel1.read(buffer);
                        String request = new String(buffer.array()).trim();
                        buffer.clear();
                        System.out.println("request:"+request);

                        String response = requestHandler.handle(request);
                        channel1.write(ByteBuffer.wrap(response.getBytes()));

                    }

                    iterator.remove();
                }


            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
